package com.lintf.bot.rabbitmq.dead;

import com.alibaba.fastjson2.JSONObject;
import com.lintf.bot.rabbitmq.AbstractCommonMessageService;
import com.lintf.bot.rabbitmq.vo.MessageRetryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @className: TtlTetsConsumer
 * @Description: TODO rabbitmq 补偿机制--重新发送业务消息
 * @author: wzq
 * @date: 2022/5/13 3:05 PM
 */
@Slf4j
public abstract class CommonMessageRetryService extends AbstractCommonMessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送延时消息
     *
     * @param message
     */
    public void retryMessage(Message message) {
        try {
            //封装消息
            MessageRetryVo retryMessageVo = buildMessageRetryInfo(message);
            log.info("重试消息：{}", retryMessageVo);
            retryMessageVo.setType(1);
            prepareAction(retryMessageVo);
        } catch (Exception exception) {
            log.warn("处理消息异常，错误信息：", exception);
        }
    }


    /**
     * 异常消息重新入库
     *
     * @param retryVo
     */
    @Override
    protected void sendMessage(MessageRetryVo retryVo) {
        //将补偿消息实体放入头部，原始消息内容保持不变
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("message_retry_info", JSONObject.toJSONString(retryVo));
        Message message = new Message(retryVo.getBodyMsg().getBytes(), messageProperties);
        rabbitTemplate.convertAndSend(retryVo.getExchangeName(), retryVo.getRoutingKey(), message);
        log.info("死信队列发送业务消息 完成 时间：{}", System.currentTimeMillis());
    }

}
